package com.wanlian.common;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import com.wanlian.model.ValitationModel;

public class BeanValitation {

	private static final ValidatorFactory vFactory = Validation.buildDefaultValidatorFactory();
	private static final Validator validator = vFactory.getValidator();

	public static ValitationModel validate(Object bean) {
		if (bean == null) {
			return new ValitationModel(false, "输入的数据有误");
		}

		String validationMessage = validateWithFirstErrorMsg(bean);
		if (validationMessage == null || validationMessage.isEmpty()) {
			return new ValitationModel(true, null);
		} else {
			return new ValitationModel(false, validationMessage);
		}
	}

	public static <T> String validateWithFirstErrorMsg(T t) {
		Set<ConstraintViolation<T>> set = validator.validate(t);
		String errorMsg = "";

		if (set != null && set.size() > 0) {
			for (ConstraintViolation<T> val : set) {
				errorMsg = val.getMessage();
				break;
			}
		}

		return errorMsg;
	}
}
